"""
数据验证器
"""
import re
from typing import Any, Dict, List, Optional
from urllib.parse import urlparse
from base.logger_manager import LoggerManager


class DataValidator:
    """数据验证器"""
    
    def __init__(self):
        self.logger = LoggerManager.get_logger("data_validator")
    
    def validate_url(self, url: str) -> bool:
        """验证URL格式"""
        try:
            result = urlparse(url)
            return all([result.scheme, result.netloc])
        except Exception:
            return False
    
    def validate_email(self, email: str) -> bool:
        """验证邮箱格式"""
        pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
        return bool(re.match(pattern, email))
    
    def validate_phone(self, phone: str) -> bool:
        """验证电话号码格式"""
        # 移除所有非数字字符
        digits = re.sub(r'\D', '', phone)
        # 检查长度（7-15位）
        return 7 <= len(digits) <= 15
    
    def validate_linkedin_url(self, url: str) -> bool:
        """验证LinkedIn URL"""
        if not self.validate_url(url):
            return False
        
        linkedin_patterns = [
            r'linkedin\.com/in/',
            r'linkedin\.com/pub/',
            r'linkedin\.com/company/',
            r'linkedin\.com/school/'
        ]
        
        return any(re.search(pattern, url.lower()) for pattern in linkedin_patterns)
    
    def validate_facebook_url(self, url: str) -> bool:
        """验证Facebook URL"""
        if not self.validate_url(url):
            return False
        
        facebook_patterns = [
            r'facebook\.com/',
            r'fb\.com/',
            r'm\.facebook\.com/'
        ]
        
        return any(re.search(pattern, url.lower()) for pattern in facebook_patterns)
    
    def validate_profile_data(self, profile_data: Dict[str, Any]) -> Dict[str, Any]:
        """验证用户档案数据"""
        validation_result = {
            "is_valid": True,
            "errors": [],
            "warnings": [],
            "cleaned_data": {}
        }
        
        # 验证必需字段
        required_fields = ["platform", "profile_id"]
        for field in required_fields:
            if field not in profile_data or not profile_data[field]:
                validation_result["errors"].append(f"缺少必需字段: {field}")
                validation_result["is_valid"] = False
        
        # 验证URL字段
        url_fields = ["profile_url", "avatar_url"]
        for field in url_fields:
            if field in profile_data and profile_data[field]:
                url = profile_data[field]
                if not self.validate_url(url):
                    validation_result["warnings"].append(f"无效的URL格式: {field}")
                else:
                    validation_result["cleaned_data"][field] = url
        
        # 验证LinkedIn URL
        if "profile_url" in profile_data and profile_data["profile_url"]:
            url = profile_data["profile_url"]
            if "linkedin" in url.lower() and not self.validate_linkedin_url(url):
                validation_result["warnings"].append("LinkedIn URL格式可能不正确")
        
        # 验证Facebook URL
        if "profile_url" in profile_data and profile_data["profile_url"]:
            url = profile_data["profile_url"]
            if "facebook" in url.lower() and not self.validate_facebook_url(url):
                validation_result["warnings"].append("Facebook URL格式可能不正确")
        
        # 清理和验证文本字段
        text_fields = ["username", "full_name", "headline", "location", "company", "industry"]
        for field in text_fields:
            if field in profile_data and profile_data[field]:
                cleaned_text = self._clean_text(profile_data[field])
                if cleaned_text:
                    validation_result["cleaned_data"][field] = cleaned_text
        
        # 验证数字字段
        number_fields = ["connections_count", "followers_count"]
        for field in number_fields:
            if field in profile_data and profile_data[field]:
                try:
                    value = int(profile_data[field])
                    if value >= 0:
                        validation_result["cleaned_data"][field] = value
                    else:
                        validation_result["warnings"].append(f"负数无效: {field}")
                except (ValueError, TypeError):
                    validation_result["warnings"].append(f"无效的数字格式: {field}")
        
        # 验证JSON字段
        json_fields = ["experience", "education", "skills", "contact_info", "raw_data"]
        for field in json_fields:
            if field in profile_data and profile_data[field]:
                if isinstance(profile_data[field], (dict, list)):
                    validation_result["cleaned_data"][field] = profile_data[field]
                else:
                    validation_result["warnings"].append(f"JSON字段格式错误: {field}")
        
        return validation_result
    
    def validate_search_parameters(self, search_params: Dict[str, Any]) -> Dict[str, Any]:
        """验证搜索参数"""
        validation_result = {
            "is_valid": True,
            "errors": [],
            "warnings": [],
            "cleaned_params": {}
        }
        
        # 验证关键词
        if "keyword" not in search_params or not search_params["keyword"]:
            validation_result["errors"].append("搜索关键词不能为空")
            validation_result["is_valid"] = False
        else:
            keyword = self._clean_text(search_params["keyword"])
            if keyword:
                validation_result["cleaned_params"]["keyword"] = keyword
            else:
                validation_result["errors"].append("搜索关键词无效")
                validation_result["is_valid"] = False
        
        # 验证平台
        valid_platforms = ["linkedin", "facebook"]
        if "platform" not in search_params:
            validation_result["errors"].append("平台参数不能为空")
            validation_result["is_valid"] = False
        elif search_params["platform"] not in valid_platforms:
            validation_result["errors"].append(f"不支持的平台: {search_params['platform']}")
            validation_result["is_valid"] = False
        else:
            validation_result["cleaned_params"]["platform"] = search_params["platform"]
        
        # 验证分页参数
        if "max_pages" in search_params:
            try:
                max_pages = int(search_params["max_pages"])
                if 1 <= max_pages <= 50:  # 限制最大页数
                    validation_result["cleaned_params"]["max_pages"] = max_pages
                else:
                    validation_result["warnings"].append("最大页数超出范围，已调整为50")
                    validation_result["cleaned_params"]["max_pages"] = 50
            except (ValueError, TypeError):
                validation_result["warnings"].append("无效的最大页数，使用默认值10")
                validation_result["cleaned_params"]["max_pages"] = 10
        
        # 验证过滤条件
        if "filters" in search_params and isinstance(search_params["filters"], dict):
            cleaned_filters = {}
            for key, value in search_params["filters"].items():
                if value and isinstance(value, str):
                    cleaned_value = self._clean_text(value)
                    if cleaned_value:
                        cleaned_filters[key] = cleaned_value
            
            if cleaned_filters:
                validation_result["cleaned_params"]["filters"] = cleaned_filters
        
        return validation_result
    
    def _clean_text(self, text: str) -> Optional[str]:
        """清理文本数据"""
        if not text or not isinstance(text, str):
            return None
        
        # 移除多余的空白字符
        cleaned = re.sub(r'\s+', ' ', text.strip())
        
        # 移除控制字符
        cleaned = re.sub(r'[\x00-\x1f\x7f-\x9f]', '', cleaned)
        
        # 限制长度
        if len(cleaned) > 1000:
            cleaned = cleaned[:1000] + "..."
        
        return cleaned if cleaned else None
    
    def validate_task_parameters(self, task_params: Dict[str, Any]) -> Dict[str, Any]:
        """验证任务参数"""
        validation_result = {
            "is_valid": True,
            "errors": [],
            "warnings": [],
            "cleaned_params": {}
        }
        
        # 验证任务类型
        valid_task_types = ["scrape", "message", "search"]
        if "task_type" not in task_params:
            validation_result["errors"].append("任务类型不能为空")
            validation_result["is_valid"] = False
        elif task_params["task_type"] not in valid_task_types:
            validation_result["errors"].append(f"不支持的任务类型: {task_params['task_type']}")
            validation_result["is_valid"] = False
        else:
            validation_result["cleaned_params"]["task_type"] = task_params["task_type"]
        
        # 验证任务ID
        if "task_id" not in task_params or not task_params["task_id"]:
            validation_result["errors"].append("任务ID不能为空")
            validation_result["is_valid"] = False
        else:
            task_id = str(task_params["task_id"]).strip()
            if len(task_id) < 3 or len(task_id) > 100:
                validation_result["errors"].append("任务ID长度必须在3-100字符之间")
                validation_result["is_valid"] = False
            else:
                validation_result["cleaned_params"]["task_id"] = task_id
        
        return validation_result
